<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">用户名</label>
                            <div class="layui-input-inline">
                                <input type="text" name="userName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">用户类型</label>
                            <div class="layui-input-inline">
                                <select name="type" >
                                    <option value="">请选择</option>
                                    <option value="0">管理员</option>
                                    <option value="1" >宿管员</option>
                                    <option value="2">学生</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button class="layui-btn layuiadmin-btn-list" lay-submit lay-filter="search-user-submit">
                                <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>
<!--        toolbarDemo就是头部工具栏的id-->
        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加用户 </button>
                <!-- <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="deletePart"> 批量删除 </button> -->

                <button class="layui-btn  layui-btn-sm " lay-event="importData" style="background: #2ecc71" > 导入数据 </button>
                <button class="layui-btn  layui-btn-sm " lay-event="exportData" style="background: #27ae60"> 导出全部 </button>

                <button class="layui-btn  layui-btn-sm " style="background: #16a085"> <i class="layui-icon">&#xe67c;</i> <a href="../static/excel/用户信息上传模板.xlsx" style="color:white">上传模版</a></button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>
<button id="importExcel" style="display: none" ></button>
<script>
    layui.use(['form', 'table','miniPage','element','upload','store'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            upload = layui.upload,
            store = layui.store,
            miniPage = layui.miniPage;

        form.render() //处理有时候下拉框会消失
        table.render({
            elem: '#currentTableId',
            id: 'user-table-id',//重载需要
            url: '/user/partList',
            method: 'post',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'print'], //头部工具栏
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'id', title: 'ID', sort: true},
                {field: 'userName', title: '用户名'},
                {field: 'name', title: '姓名'},
                {field: 'phone', title: '联系方式', minWidth: 150},
                {
                    field: 'type', title: '用户类型', templet: function (d) {
                        if (d.type == 0) return '<button type="button" class="layui-btn  layui-btn-radius layui-btn-xs">管理员</button>';
                        else if (d.type == 1) return '<button type="button" class="layui-btn layui-btn-normal layui-btn-radius layui-btn-xs">宿管员</button>';
                        else if (d.type == 2) return '<button type="button" class="layui-btn layui-btn-warm layui-btn-radius layui-btn-xs">学生</button>';
                    }
                },
                {field: 'remark', title: '备注', sort: true},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
            ]],
            limits: [5, 10, 15, 20, 25, 50, 100],
            limit: 10,
            skin: 'line',
            page: true,//开启分页
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.users.total, //解析数据长度
                    "data": res.data.users.records //解析数据列表
                };
            }
        });
        // console.log(table)
        // 监听搜索操作
        form.on('submit(search-user-submit)',function (data) {
            table.reload('user-table-id',{
                where:{
                    "userName":data.field.userName,
                    "type":data.field.type
                }
            });
            return false;
        });



        /**
         * toolbar(表格头部工具栏)
         * tabel.on 事件监听
         * 监听表格的头部工具栏
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            switch (obj.event) {
                case "add":{
                    var content = miniPage.getHrefContent('user/add.html');
                    var openWH = miniPage.getOpenWidthHeight();

                    var index = layer.open({
                        title: '添加用户',
                        type: 1,//页面层
                        shade: 0.2,
                        maxmin:false,
                        shadeClose: true,
                        area: [openWH[0] + 'px', openWH[1] + 'px'],
                        offset: [openWH[2] + 'px', openWH[3] + 'px'],
                        content: content,
                    });
                    $(window).on("resize", function () {
                        layer.full(index);
                    });
                    break;
                }
                case "deletePart":{
                    var data = table.checkStatus('user-table-id').data
                    console.log(data)
                    if(data.length==0){
                        layer.msg("请至少选择一条数据删除")
                    }else{
                        layer.confirm('真的要删除这些用户数据吗？', function (index) {
                            let userIds = data.map(item=>item.id)
                            userIdsStr = userIds.join(",")
                            console.log(userIdsStr)
                            axios.post("user/deletePart/"+userIdsStr)
                                .then(data=>{
                                    layer.msg("删除成功",{
                                    },function () {
                                        table.reload("user-table-id")
                                    })
                                }).catch(error=>{
                                layer.msg("删除失败")
                            });
                        });
                    }
                    break;
                }
                case "importData":{
                    $("#importExcel").click();
                    break;
                }
                case "exportData":{
                    layer.confirm('确定导出所有用户信息吗？', {
                        btn: ['确定', '取消']
                    }, function(index){
                        //window.open("http://localhost:8888/dormitory/user/exportAll"); 这种办法不安全
                        axios({
                            method: 'get',
                            url:'/user/exportAll',
                            responseType: 'blob',   // 重要， 限制返回的数据结构为blob格式，方便前端做转换
                        }).then(data=>{
                            const link = document.createElement('a')
                            const blob = new Blob([data], { type: 'application/vnd.ms-excel' })
                            link.style.display = 'none'
                            link.href = URL.createObjectURL(blob)
                            link.setAttribute('download','用户信息.xlsx')
                            document.body.appendChild(link)
                            link.click()
                            document.body.removeChild(link)
                        })
                        layer.close(index);
                    }, function(index){
                        
                    });
                    break;
                }
            }

        });
        upload.render({
            elem:'#importExcel',
            url:'/user/addUsers',
            size : '5000',//文件最大可允许上传的大小，单位 KB
            accept:'file',//允许上传文件
            exts:'xls|xlsx|xlsm|xlt|xltx|xltm',
            field:'uploadFile',
            headers: {token: store.getToken()},
            done:function (result) {//执行上传请求后的回调。返回三个参数，分别为：res（服务端响应信息）、index（当前文件的索引）、upload（重新上传的方法，一般在文件上传失败后使用）
                console.log(result);
                if(result.code==0){
                  layer.msg(result.message, {
                        icon: 6,
                        time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    }, function(){
                      table.reload("user-table-id");
                  })
                }else{
                  layer.msg(result.message,{
                        icon: 5,
                        time: 2000, //2秒关闭（如果不配置，默认是3秒）
                        anim:6
                  });
                }
            }
        });
        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {

                var content = miniPage.getHrefContent('user/edit.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '编辑用户',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                });
                form.val("edit-user", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                    "id":data.id,
                    "userName":data.userName,
                    "password":data.password,
                    "name":data.name,
                    "phone":data.phone,
                    "type":data.type,
                    "remark":data.remark
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                //如果是学生 提示到学生管理中删除
                if(data.type==2){
                  layer.msg("到[学生管理]中删除学生哦！",{
                        icon: 5,
                        time: 2000, //2秒关闭（如果不配置，默认是3秒）
                        anim:6
                      });
                }else{
                  layer.confirm('真的要删除该用户数据吗？', function (index) {
                    axios({
                        method:'post',
                        url:'/user/deleteOne/'+data.id
                    }).then(data=>{
                      if(data.code==0){
                        layer.msg(data.message, {
                          icon: 6,
                          time: 2000 //2秒关闭（如果不配置，默认是3秒）
                        }, function(){
                          table.reload("user-table-id")
                        });
                      }else{
                        layer.msg(data.message,{
                          icon: 5,
                          time: 2000, //2秒关闭（如果不配置，默认是3秒）
                          anim:6
                        });  
                      }
                    }).catch(error=>{
                      layer.msg("请求错误",{
                        icon: 5,
                        time: 2000, //2秒关闭（如果不配置，默认是3秒）
                        anim:6
                      });
                    });
                    layer.close(index);
                  });
                }
            }
        });

    });
</script>